package com.lvtongka.app.ui.login

import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Build
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.lvtongka.app.BuildConfig
import com.lvtongka.app.R
import com.lvtongka.app.base.BaseActivity
import com.lvtongka.app.common.AppUtils
import com.lvtongka.app.common.VerifyCodeCountDownTimer
import com.lvtongka.app.common.config.BaseUIConfig
import com.lvtongka.app.common.listener.CountDownCallback
import com.lvtongka.app.databinding.ActivityLoginRevisionBinding
import com.lvtongka.app.dialog.PrivateDialog
import com.lvtongka.app.helper.SPHelper
import com.lvtongka.app.http.common.WebConstants
import com.lvtongka.app.ui.HomeActivity
import com.mobile.auth.gatewayauth.AuthRegisterViewConfig
import com.mobile.auth.gatewayauth.AuthUIConfig
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.PreLoginResultListener
import com.mobile.auth.gatewayauth.ResultCode
import com.mobile.auth.gatewayauth.TokenResultListener
import com.mobile.auth.gatewayauth.model.TokenRet


/**
 * describe:
 * 登录
 * @author:ZhangWei(张伟)
 * date:2024/12/23
 * time:12:23
 */
class LoginRevisionActivity : BaseActivity<ActivityLoginRevisionBinding, LoginViewModel>(){
    private val TAG = "LoginRevisionActivity_zw_test"
    var isPhoneCompiler = false
    var isChangeBack = false
    var downTimer: VerifyCodeCountDownTimer? = null
    private var isXy = false
    // 一键登录
    private var mPhoneNumberAuthHelper: PhoneNumberAuthHelper? = null
    private var mCheckListener: TokenResultListener? = null
    private var mTokenResultListener: TokenResultListener? = null
    private var sdkAvailable = true
    private var mUIConfig: BaseUIConfig? = null
    private var token: String? = null

    private var isPause = false

    override fun initViewModel(): LoginViewModel {
        return ViewModelProvider(this)[LoginViewModel::class.java]
    }

    override fun initEvent() {
        initXy()
        binding.etPhone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                // 文本改变之前的回调，可以在这里做一些处理
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                // 文本正在改变的回调，可以在这里做一些处理
            }

            override fun afterTextChanged(s: Editable) {
                // 文本改变之后的回调，可以在这里做一些处理，比如检查电话号码是否完成
                val phoneNumber = s.toString()
                if (AppUtils.isPhoneNumberValid(phoneNumber)) {
                    // 电话号码输入完成，执行后续操作
                    isPhoneCompiler = true
                    binding.tvGetCode.isEnabled = true
                } else {
                    if (isPhoneCompiler) {
                        isChangeBack = false
                        binding.tvGetCode.isEnabled = false
                    }
                }
            }
        })
        binding.etSmsCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                // 文本改变之前的回调，可以在这里做一些处理
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                // 文本正在改变的回调，可以在这里做一些处理
            }

            override fun afterTextChanged(s: Editable) {
                // 文本改变之后的回调，可以在这里做一些处理，比如检查电话号码是否完成
                val codeNumber = s.toString()
                if (isCodeNumberValid(codeNumber)) {
                    // 验证码输入完成，执行后续操作
                    isChangeBack = true
                    if (isXy) {
                        binding.tvGoLogin.setBackgroundResource(R.drawable.bg_button_red)
                        binding.tvGoLogin.setTextColor(getColor(R.color.white))
                        binding.tvGoLogin.isEnabled = true
                    }
                } else {
                    if (isChangeBack) {
                        isChangeBack = false
                        binding.tvGoLogin.setBackgroundResource(R.drawable.home_item_brith_bg4)
                        binding.tvGoLogin.setTextColor(getColor(R.color.text666666))
                        binding.tvGoLogin.isEnabled = false
                    }
                }
            }
        })
        binding.tvOneClickLogin.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            onClickLogin()
        }

        binding.llAccess.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            checkRadio()
        }

        binding.tvGetCode.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            showLoading("获取中...")
            viewModel.sendSmsCode(binding.etPhone.text.toString())
        }

        binding.tvGoLogin.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            val phone = binding.etPhone.text.toString()
            val code = binding.etSmsCode.text.toString()
            if (!isXy) {
                showToast("请阅读协议并同意")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(phone)) {
                showToast("请输入手机号")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(code)) {
                showToast("请输入验证码")
                return@setOnClickListener
            }
            showLoading("登录中...")
            viewModel.sendSmsLogin(phone, code)
        }

        viewModel.error.observe(this) {
            hideLoading()
            showToast(it)
        }

        viewModel.sendAt.observe(this) {
            hideLoading()
            if (!TextUtils.isEmpty(it.send_at)) {
                downTimer = VerifyCodeCountDownTimer(
                    binding.tvGetCode,
                    60000L,
                    1000L,
                    object : CountDownCallback {
                        override fun onFinish() {
                            binding.tvGetCode.isClickable = true
                            downTimer = null
                        }
                    })
                downTimer?.start()
            }
        }
        viewModel.result.observe(this) {
            hideLoading()
            showToast("登录成功")
            AppUtils.initBugly(this)
            startActivity(Intent(this, HomeActivity::class.java))
            setResult(RESULT_OK)
            finish()
        }
    }

    private fun checkRadio(){
        isXy = !isXy
        if (isXy) {
            binding.ivCb.setImageResource(R.mipmap.icon_pay_selected)
        } else {
            binding.ivCb.setImageResource(R.mipmap.icon_pay_select_un)
        }
        if (isCodeNumberValid(binding.etSmsCode.text.toString())) {
            // 验证码输入完成，执行后续操作
            if (isXy) {
                binding.tvGoLogin.setBackgroundResource(R.drawable.bg_button_red)
                binding.tvGoLogin.setTextColor(getColor(R.color.white))
                binding.tvGoLogin.isEnabled = true
            } else {
                binding.tvGoLogin.setBackgroundResource(R.drawable.home_item_brith_bg4)
                binding.tvGoLogin.setTextColor(getColor(R.color.text666666))
                binding.tvGoLogin.isEnabled = false
            }
        } else {
            binding.tvGoLogin.setBackgroundResource(R.drawable.home_item_brith_bg4)
            binding.tvGoLogin.setTextColor(getColor(R.color.text666666))
            binding.tvGoLogin.isEnabled = false
        }
    }

    override fun initData() {
        binding.tvGetCode.isEnabled = false
        binding.tvGoLogin.isEnabled = false
        sdkInit(BuildConfig.AUTH_SECRET)
        mUIConfig = BaseUIConfig.init(this, mPhoneNumberAuthHelper)

        isXy = SPHelper.getBoolean("accept", false)
        if (isXy) {
            AppUtils.initBugly(this)
            binding.ivCb.setImageResource(R.mipmap.icon_pay_selected)
        } else {
            binding.ivCb.setImageResource(R.mipmap.icon_pay_select_un)
        }
    }

    override fun initBinding(): ActivityLoginRevisionBinding {
        return ActivityLoginRevisionBinding.inflate(layoutInflater)
    }

    private fun isCodeNumberValid(codeNumber: String): Boolean {
        // 这里可以添加你的电话号码验证逻辑
        return codeNumber.length == 6
    }

    private fun initXy() {
        val tvProtocol = SpannableStringBuilder(binding.tvXy.text.toString())
        tvProtocol.setSpan(
            CliclSpan(this, 1),
            7,
            20,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        tvProtocol.setSpan(
            CliclSpan(this, 2),
            20,
            31,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        tvProtocol.setSpan(
            CliclSpan(this, 3),
            31,
            40,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        binding.tvXy.text = tvProtocol
        binding.tvXy.movementMethod = LinkMovementMethod.getInstance()
    }

    inner class CliclSpan : ClickableSpan {
        var mContext: Context? = null
        var mNum: Int? = null

        constructor() : super()
        constructor(context: Context?, num: Int?) {
            mContext = context
            mNum = num
        }

        override fun onClick(widget: View) {
            var url = ""
            when(mNum) {
                1-> {
                    url = "https://e.189.cn/sdk/agreement/detail.do?hidetop=true"
                }
                2->{
                    url = WebConstants.PRIVACY_AGREEMENT
                }
                3->{
                    url = WebConstants.PROVACY_MAIN
                }
            }
            if (!TextUtils.isEmpty(url)) {
                jumpWeb(url, true)
            }
        }

        override fun updateDrawState(ds: TextPaint) {
            ds.color = ContextCompat.getColor(mContext!!, R.color.btn_bg_color1)
            ds.isUnderlineText = false
        }
    }


    private fun onClickLogin() {
        if (sdkAvailable) {
            configLoginTokenPort()
            getLoginToken(5000)
        } else {
            //如果环境检查失败 使用其他登录方式
            mPhoneNumberAuthHelper!!.setAuthListener(null)
        }
    }

    private fun sdkInit(secretInfo: String?) {
        mCheckListener = object : TokenResultListener {
            override fun onTokenSuccess(s: String) {
                try {
                    val pTokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_ERROR_ENV_CHECK_SUCCESS == pTokenRet.code) {
                        accelerateLoginPage(5000)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                sdkAvailable = false
                //终端环境检查失败之后 跳转到其他号码校验方式
            }
        }
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(this, mCheckListener)
        mPhoneNumberAuthHelper!!.reporter.setLoggerEnable(true)
        mPhoneNumberAuthHelper!!.setAuthSDKInfo(secretInfo)
        mPhoneNumberAuthHelper!!.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN)
    }

    /**
     * 在不是一进app就需要登录的场景 建议调用此接口 加速拉起一键登录页面
     * 等到用户点击登录的时候 授权页可以秒拉
     * 预取号的成功与否不影响一键登录功能，所以不需要等待预取号的返回。
     * @param timeout
     */
    fun accelerateLoginPage(timeout: Int) {
        mPhoneNumberAuthHelper!!.accelerateLoginPage(timeout, object : PreLoginResultListener {
            override fun onTokenSuccess(s: String) {
                Log.e(TAG,"预取号成功: $s")
            }

            override fun onTokenFailed(s: String, s1: String) {
                Log.e(TAG,"预取号失败：, $s1")
            }
        })
    }

    /**
     * 拉起授权页
     * @param timeout 超时时间
     */
    private fun getLoginToken(timeout: Int) {
        mUIConfig!!.configAuthPage()
        mTokenResultListener = object : TokenResultListener {
            override fun onTokenSuccess(s: String) {
                hideLoading()
                var tokenRet: TokenRet? = null
                try {
                    tokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_START_AUTHPAGE_SUCCESS == tokenRet.code) {

                    }

                    if (ResultCode.CODE_SUCCESS == tokenRet.code) {

                        token = tokenRet.token
                        getResultWithToken(token)
                        mPhoneNumberAuthHelper!!.setAuthListener(null)
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                Log.e(TAG,"获取token失败：$s")

                hideLoading()
                mPhoneNumberAuthHelper!!.hideLoginLoading()
                //如果环境检查失败 使用其他登录方式
                var tokenRet: TokenRet? = null
                try {
                    tokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_ERROR_USER_CANCEL != tokenRet!!.code) {
                        Toast.makeText(
                            applicationContext,
                            "一键登录失败切换到其他登录方式",
                            Toast.LENGTH_SHORT
                        ).show()

                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
                mPhoneNumberAuthHelper!!.quitLoginPage()
                mPhoneNumberAuthHelper!!.setAuthListener(null)
            }
        }
        mPhoneNumberAuthHelper!!.setAuthListener(mTokenResultListener)
        mPhoneNumberAuthHelper!!.getLoginToken(this, timeout)
        showLoading("正在唤起授权页")
    }

    fun getResultWithToken(token: String?) {
        // 调用登录
        token?.let {
            showLoading("正在登录...")
            viewModel.fastLogin(it)
        }
        mPhoneNumberAuthHelper!!.quitLoginPage()
    }


    /**
     * 配置竖屏样式
     */
    private fun configLoginTokenPort() {
        mPhoneNumberAuthHelper!!.removeAuthRegisterXmlConfig()
        mPhoneNumberAuthHelper!!.removeAuthRegisterViewConfig()
        mPhoneNumberAuthHelper!!.addAuthRegistViewConfig("switch_acc_tv",
            AuthRegisterViewConfig.Builder()
                .setView(initDynamicView())
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .setCustomInterface { mPhoneNumberAuthHelper!!.quitLoginPage() }.build()
        )
        var authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
        if (Build.VERSION.SDK_INT == 26) {
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND
        }
        mPhoneNumberAuthHelper!!.setAuthUIConfig(
            AuthUIConfig.Builder()
                .setAppPrivacyOne("《自定义隐私协议》", "https://www.baidu.com")
                .setAppPrivacyColor(Color.GRAY, Color.parseColor("#002E00"))
                .setPrivacyState(false)
                .setCheckboxHidden(true)
                .setStatusBarColor(Color.TRANSPARENT)
                .setStatusBarUIFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
                .setLightColor(true)
                .setAuthPageActIn("in_activity", "out_activity")
                .setAuthPageActOut("in_activity", "out_activity")
                .setProtocolShakePath("protocol_shake")
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
                .setLogoImgPath("icon_login_logo")
                .setScreenOrientation(authPageOrientation)
                .create()
        )
    }

    private fun initDynamicView(): View {
        val switchTV = TextView(this)
        val mLayoutParams2 = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, AppUtils.dip2px(50f)
        )
        mLayoutParams2.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
        mLayoutParams2.setMargins(0, AppUtils.dip2px(450f), 0, 0)
        switchTV.text = "-----  自定义view  -----"
        switchTV.setTextColor(0x666667)
        switchTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13.0f)
        switchTV.layoutParams = mLayoutParams2
        return switchTV
    }


    override fun onPause() {
        super.onPause()
        isPause = true
    }

    override fun onResume() {
        super.onResume()
        if (isPause) {
            isPause = false
        } else {
            val isAccept = SPHelper.getBoolean("accept", false)
            if (!isAccept) {
                showDialog()
            }
        }
    }

    private fun showDialog() = PrivateDialog.getInstance()
        .setOnTipItemClickListener(object : PrivateDialog.OnTipItemClickListener {
            override fun cancleClick() {
                finish()
            }

            override fun sureClick() {
                SPHelper.putBoolean("accept", true)
                isXy = true
                binding.ivCb.setImageResource(R.mipmap.icon_pay_selected)
            }

            override fun userClick() {
                //跳转至用户服务协议
                jumpWeb(WebConstants.PRIVACY_AGREEMENT, true)
            }

            override fun termsClick() {
                //跳转至隐私政策
                jumpWeb(WebConstants.PROVACY_MAIN, true)
            }
        }).create(this)
}